import type { Directive, DirectiveBinding } from 'vue'
import { useUserStore } from '@/stores'

/**
 * 按钮权限控制指令
 * 用法: v-has="'acl:user:add'" 或 v-has="['acl:user:add', 'acl:user:edit']"
 * 说明: 当用户拥有指定权限(任意一个)时显示元素,否则移除元素
 */
export const hasPermission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const userStore = useUserStore()

    // 获取用户的按钮权限列表
    const userButtons = userStore.userInfo?.buttons || []

    if (value) {
      let hasPermission = false

      if (typeof value === 'string') {
        // 单个权限判断
        hasPermission = userButtons.includes(value)
      } else if (Array.isArray(value)) {
        // 多个权限判断 (任意一个满足即可)
        hasPermission = value.some((permission) => userButtons.includes(permission))
      }

      // 如果没有权限,则移除该元素
      if (!hasPermission) {
        el.parentNode?.removeChild(el)
      }
    }
  },
}

/**
 * 按钮权限控制指令(要求所有权限都满足)
 * 用法: v-has-all="['acl:user:add', 'acl:user:edit']"
 * 说明: 当用户拥有所有指定权限时显示元素,否则移除元素
 */
export const hasAllPermissions: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const userStore = useUserStore()

    const userButtons = userStore.userInfo?.buttons || []

    if (Array.isArray(value) && value.length > 0) {
      // 所有权限都必须满足
      const hasAllPermissions = value.every((permission) => userButtons.includes(permission))

      if (!hasAllPermissions) {
        el.parentNode?.removeChild(el)
      }
    }
  },
}
